import { ZegoExpressEngine } from "zego-express-engine-miniprogram"

export async function getToken(tokenUrl, userID, appID) {
  const res = await uni.request({
    url: tokenUrl,
    method: "get",
    data: {
      app_id: appID,
      id_name: userID
    }
  })
  return res[1].data
}


export class CommonExpress {
  appID = 1739272706
  server = "wss://webliveroom-test.zego.im/ws"
  tokenURL = "https://wsliveroom-alpha.zego.im:8282/token"
  userID
  userName
  streamID
  livePlayerList = [] // 流列表
  roomUserList = [] // 房间用户列表

  get zegoApi() {
    return CommonExpress.zegoEngine
  }

  constructor() {
    this.initSDK()
    this.zgOnListener()
  }

  async initSDK() {
    try {
      CommonExpress.zegoEngine = new ZegoExpressEngine(this.appID, this.server)
      this.zegoApi.setDebugVerbose(false)
      // this.zegoApi.setLogConfig({ logLevel: 'warn' })

    } catch (error) {
      console.error("error in initsdk", error);
    }
  }

  async checkSystemRequirements() {
    const result = await this.zegoApi.checkSystemRequirements()
    let hasCamera = false
    let hasRecord = false
    if (result.code === 10002) {
      hasCamera = await uni.authorize({
        scope: "scope.camera"
      })
      hasRecord = await uni.authorize({
        scope: "scope.record"
      })
      const requireRes = JSON.stringify(hasCamera).includes("authorize:ok") && JSON.stringify(hasRecord).includes("authorize:ok")
      return requireRes
    }
    return true
  }

  async login(roomID) {
    this.userID = "wxmini" + Date.now()
    this.userName = "nick" + this.userID
    this.token = await getToken(this.tokenURL, this.userID, this.appID)
    let isLogin = await this.zegoApi.loginRoom(
      roomID,
      this.token,
      {
        userID: this.userID,
        userName: this.userName
      },
      {
        userUpdate: true
      }
    )
    console.warn("mytag isLogin", isLogin)
  }

  async getPublishStream() {
    this.streamID = "wxRtc" + Date.now()
    const res = await this.zegoApi.startPublishingStream(this.streamID)
    return res
  }

  async getPlayStream(streamItem) {
    let playRes = await this.zegoApi.startPlayingStream(streamItem.streamID);
    this.livePlayerList.push(playRes)
  }

  zgOffListener() {
    for (const key in this.listener) {
      if (Object.hasOwnProperty.call(this.listener, key)) {
        this.zegoApi.off(key, this.listener[key])
      }
    }
  }

  zgOnListener() {
    for (const key in this.listener) {
      if (Object.hasOwnProperty.call(this.listener, key)) {
        this.zegoApi.on(key, this.listener[key].bind(this))
      }
    }
  }

  listener = {
    // RTC *******************
    // 推流质量回调
    publishQualityUpdate() {
      // console.log("mytag listen publishQualityUpdate", arguments)
    },
    // 推流状态回调
    publisherStateUpdate() {
      console.log("mytag listen publisherStateUpdate", arguments)
    },
    // 房间内流变化回调
    roomStreamUpdate(roomID, updateType, streamList) {
      if (updateType === "ADD") {
        streamList.forEach(streamItem => {
          this.getPlayStream(streamItem)
        });
      } else if (updateType === "DELETE") (
        streamList.forEach(streamItem => {
          const ind = this.livePlayerList.findIndex(item => item.streamID === streamItem.streamID)
          this.livePlayerList.splice(ind, 1)
        })
      )
    },
    // 拉流质量回调, 每次回调间隔3s
    playQualityUpdate() {
      // console.log("mytag listen playQualityUpdate", arguments)
    },
    // 接收对端设置的流附加信息
    streamExtraInfoUpdate() {
      console.log("mytag listen streamExtraInfoUpdate", arguments)
    },
    //  拉流状态回调
    playerStateUpdate() {
      console.log("mytag listen playerStateUpdate", arguments)
    },

    // RTM ******************* 事件监听
    // 当房间用户发生变化时触发
    roomUserUpdate(roomID, updateType, userList) {
      try {
        if (updateType === "ADD") {
          userList.filter(item => item.userID !== this.userID).forEach(item => {
            this.roomUserList.push(item)
          })
        } else if (updateType === "DELETE") {
          userList.forEach((user) => {
            const i = this.roomUserList.findIndex((item) => item.userID === user.userID);
            this.roomUserList.splice(i, 1);
          });
        }
      } catch (error) {
        console.error("error roomUserUpdate", error);
      }
    },
    // 房间和服务器之间的连接状态发生变化时触发
    roomStateUpdate() {
      console.log("mytag listen roomStateUpdate", arguments)
    },
    // 房间内人数发生改变时触发
    roomOnlineUserCountUpdate() {
      console.log("mytag listen roomOnlineUserCountUpdate", arguments)
    },
    // 房间广播消息通知
    IMRecvBroadcastMessage() {
      console.log("mytag listen IMRecvBroadcastMessage", arguments)
    },
    // 房间弹幕消息通知
    IMRecvBarrageMessage() {
      console.log("mytag listen IMRecvBarrageMessage", arguments)
    },
    // 监听自定义信令通知
    IMRecvCustomCommand() {
      console.log("mytag listen IMRecvCustomCommand", arguments)
    },
    // 监听房间附加消息通知
    roomExtraInfoUpdate() {
      console.log("mytag listen roomExtraInfoUpdate", arguments)
    },
  }

}


// export const commonExpress = new CommonExpress()

